import sys
import time

import pymysql
from pymysql import Connection, DatabaseError, Error

from common.time_util import time_to_string
from common.yml_util import read_yml


class DbUtil:

    def __init__(self, table_name: str, db_params: dict):
        """
        类对象初始化
        :param table_name: 表名
        :param db_params: 数据库参数，字典
        """
        assert isinstance(db_params, dict), "db_params 参数是字典格式"
        try:
            self.conn = pymysql.connect(**db_params)
            self.cur = self.conn.cursor()
            self.table = table_name
        except Error as err:
            print(f"=======连接异常========:{err.args}")

    @property
    def get_connect(self):
        return self.conn

    @property
    def get_cur(self):
        return self.cur

    def _execute(self, exc_sql, msg):
        """
        执行sql
        :param exc_sql: sql语句
        :param msg:
        :return:
        """
        print(f"sql:{exc_sql}")
        try:
            effect_rows = self.cur.execute(exc_sql)
            self.conn.commit()
            print(f"==============执行{msg}操作:{effect_rows}===========")
            return True
        except Error as err:
            self.conn.rollback()
            print(f"=======执行{msg}操作失败========:{err.args}")
            return False

    def do_select(self, _sql):
        self._execute(_sql, '查询')
        return self.cur.fetchall()

    def do_update(self, _sql):
        self._execute(_sql, '修改')

    def __del__(self):
        self.cur.close()
        self.conn.close()


if __name__ == '__main__':
    DB_CONFIG = {
        "user": "root",
        "password": "root8.1",
        "host": "localhost",
        "port": 3306,
        "database": "train-sql",
        "charset": "utf8"
    }

    sql = "SELECT * from teacher"
    sql_update = "update student set s_birth='%s' where s_id=%d" % ('1992-02-12', 1)
    # sql_insert = "insert into teacher (t_name, create_time)values ('%s', '%s')" % ('小明', time_to_string(format_=None))
    # sql_delete = "delete from teacher where t_id=%s" %(5)
    du = DbUtil("student", DB_CONFIG)
    results = du.do_select(sql)
    print(results)
    # du.do_update(sql_update)

    # with DbUtil(host='localhost', user='root', password='root8.1', port=3306, db_name='train-sql') as db:
    #     db.execute(sql)
    #     # stu_list = db.fetchall()
    #     # print(type(results))
    #     print(f"stu_list={db}")
    #     for i in db:
    #         print(i)
